package com.camera.yl.v

import android.text.Html
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.camera.base.Log.YLogImpl
import com.camera.base.bean.CameraCfg
import com.camera.base.inerface.FullEventListener
import com.camera.base.util.CameraDegreeUtil
import com.camera.base.util.EventEnum
import com.camera.base.v.BaseActivity
import com.camera.routemodule.RouterPath
import com.camera.yl.R
import com.camera.yl.databinding.ActivityCameraBinding
import com.camera.yl.v.models.CameraViewModel
import com.camera.yl.views.CameraManager
import com.camera.yl.widght.RecordingButton
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


@AndroidEntryPoint
@Route(path = RouterPath.path.camera_activity)
class CameraActivity: BaseActivity<ActivityCameraBinding,CameraViewModel>(), SurfaceHolder.Callback {
    private val TAG = "CameraActivity";
    override val viewModelClass: Class<CameraViewModel>
        get() = CameraViewModel::class.java
    lateinit var mSurfaceView: SurfaceView
    private var mPopView: View? = null
    private var mPopupWindow: PopupWindow? = null
    override fun getLayoutId(): Int {
        return R.layout.activity_camera
    }
    override fun getStatusBarColor(): Int{
        return R.color.title_background_color
    }

    override fun loadData()  {
        mBinding.viewModel = viewModel
        if (CameraManager.isRecord()) {
            mBinding.rbActivityCameraRecord.toggleRecording()
        }
        mBinding.rbActivityCameraRecord.setOnRecordingClickListener(RecordingButton.OnRecordingClickListener {
            if (it) {
                CameraManager.startRecord {
                    if (!it.success) {
                        lifecycleScope.launch(Dispatchers.Main) {
                            mBinding.rbActivityCameraRecord.toggleRecording()
                        }
                    }
                }
            }else{
                CameraManager.stopRecord()
            }
        })
        mBinding.ifbActivityCameraPhotos.setOnCameraClickListener {
            CameraManager.capture()
        }
    }
    override fun initView() {
        YLogImpl.d(TAG,"initView")
        CameraManager.icpInterface?.let { camera ->
            YLogImpl.d(TAG,"initView TRUE")
            viewModel.flashSwitch.observe(this)  {
                if (it) mBinding.ibActivityCameraSwitchFlash.setBackgroundResource(R.drawable.flash_on)
                else mBinding.ibActivityCameraSwitchFlash.setBackgroundResource(R.drawable.flash_off)
            }
            CameraManager.addEventListener(mCameraBinderEventListener)
            if (camera.isICPCameraOpen){
                addSurfaceView()
            }else{
                CameraManager.openCamera()
            }

        }


    }
    override fun onDestroy() {
        CameraManager.removeEventListener(mCameraBinderEventListener)
        super.onDestroy()
    }

    override fun surfaceCreated(p0: SurfaceHolder) {
        CameraManager.add2CameraSurface(p0.surface,mSurfaceView.width,mSurfaceView.height)
    }

    override fun surfaceChanged(p0: SurfaceHolder, p1: Int, p2: Int, p3: Int) {
    }

    override fun surfaceDestroyed(p0: SurfaceHolder) {
        CameraManager.removeWCameraSurface(p0.surface)
    }

    fun myClick(view: View) {
        Log.e(TAG, "myClick: " )
    }
    var mCameraBinderEventListener: FullEventListener = object: FullEventListener(){
        override fun onFullEventListener(type: Int, data: Any?) {
            when(type){
                EventEnum.RESULT_OPEN_CAMERA ->{
                    lifecycleScope.launch(Dispatchers.Main){
                        addSurfaceView()
                    }
                }
                EventEnum.RESULT_RECORD_ERROR ->{
                    Log.e(TAG, "onFullEventListener: RESULT_RECORD_ERROR" )
                    //录制报错
                    lifecycleScope.launch(Dispatchers.Main){
                        mBinding.rbActivityCameraRecord!!.toggleRecording()
                    }
                }
                EventEnum.RESULT_START_RECORD ->{
                    lifecycleScope.launch(Dispatchers.Main){
                        if(!mBinding.rbActivityCameraRecord.isRecording){
                            mBinding.rbActivityCameraRecord.toggleRecording()
                        }
                    }
                }
                EventEnum.RESULT_STOP_RECORD ->{
                    lifecycleScope.launch(Dispatchers.Main){
                        if(mBinding.rbActivityCameraRecord.isRecording){
                            mBinding.rbActivityCameraRecord.toggleRecording()
                        }
                    }
                }
                EventEnum.RESULT_CAPTURE_SUCCESS ->{

                }

            }
        }
    }

    fun onCameraClick(view: View) {
        when(view.id){
            R.id.ib_activity_camera_switch_camera -> {
                switchCamera()
            }
            R.id.ib_activity_camera_zoom_up -> {
                CameraManager.zoomUp()
            }
            R.id.ib_activity_camera_zoom_down -> {
                CameraManager.zoomDown()
            }
            R.id.ib_activity_camera_switch_flash -> {
                viewModel.flash()
            }
        }
    }

    private fun switchCamera() {
        //切换摄像头
        if (viewModel.cameraList?.size!! <= 2) {
            //如果只有两个摄像头  直接旋转
            //移出surfaceview
            removeSurfaceView()
            CameraManager.switchCamera()
            viewModel.switchCamera()
            //nightVisibility.value = if(icpInterface.getCameraSuperNight() > 0) View.VISIBLE else View.GONE
            //重新添加SurfaceView
        } else {
            //如果有多个摄像头侧边弹出popupwindow 列表选择
            showPopWindow(mBinding.ibActivityCameraSwitchCamera,CameraManager.getCameras())
        }

    }

    /**
     * 添加预览surface
     */
    private fun addSurfaceView() {
        mSurfaceView = SurfaceView(this@CameraActivity)
        mSurfaceView.getHolder().addCallback(this@CameraActivity)
        CameraManager.icpInterface?.let {
            YLogImpl.d(TAG,"DEGREE:${CameraManager.icpInterface?.getCameraPreviewGgree()}  系统获取角度:${CameraDegreeUtil.getDisplayOrientation(0)}" )
            it.reLayoutSurfaceView(
                this@CameraActivity,
                mBinding.flActivityCameraSurface, CameraManager.icpInterface?.recordSize!!,
                if (CameraManager.icpInterface?.getCameraPreviewGgree() == -1)
                             CameraDegreeUtil.getDisplayOrientation(0)
                         else
                             CameraManager.icpInterface!!.getCameraPreviewGgree(),
                -1, true
            )
        }
        mBinding.flActivityCameraSurface.addView(mSurfaceView)
    }

    /**
     * 去除surface
     */
    private fun removeSurfaceView(){
        mBinding.flActivityCameraSurface.removeView(mSurfaceView)
    }

    /**
     * 显示摄像头选择的popupwindow
     * @param view View?
     * @param cameraTexts List<CameraCfg>?
     */
    fun showPopWindow(view: View?, cameraTexts: List<CameraCfg>?) {
        // TODO Auto-generated method stub
        if (mPopupWindow != null && mPopupWindow!!.isShowing){
            mPopupWindow!!.dismiss()
            return
        }
        mPopView = layoutInflater.inflate(R.layout.popupwindow_switch_cameras, null)
        val ll = mPopView!!.findViewById<LinearLayout>(R.id.ll_popupwindow_switch_cameras);
        cameraTexts?.forEach {
            val t = TextView(this)
            t.text = Html.fromHtml("<u>"+ it.flag +"</u>")
            t.setOnClickListener { viewid ->
                removeSurfaceView()
                CameraManager.switchCamera(it.camera_id)
                viewModel.switchCamera()
                mPopupWindow!!.dismiss()
            }
            ll.addView(t)
        }
        mPopupWindow = PopupWindow(
            mPopView,
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        mPopupWindow!!.contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
        val popupWidth: Int = mPopupWindow!!.contentView.measuredWidth
        val popupHeight: Int = mPopupWindow!!.contentView.measuredHeight
        val yoff: Int = -(popupHeight + view!!.height) / 2
        mPopupWindow!!.showAsDropDown(view, 0, -(popupHeight + view!!.height));
    }
}